package util

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/net/ghttp"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"strconv"
	"time"
)

func WriteFile(path string, data []byte) { // 写数据到文件
	f, err := os.Create(path)
	if err != nil {
		panic(err)
	}

	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			panic(err)
		}
	}(f)

	_, err = f.Write(data)
	if err != nil {
		panic(err)
	}
}

func IsFileExist(filename string, filesize int64) bool {
	info, err := os.Stat(filename)
	if os.IsNotExist(err) {
		fmt.Println(info)
		return false
	}

	if filesize == info.Size() {
		fmt.Println("安装包已存在！", info.Name(), info.Size(), info.ModTime())
		return true
	}

	err = os.Remove(filename)
	if err != nil {
		panic(err)
	}

	return false
}
func downloadFile(url, localPath string, fb func(length, downLen int64)) error {
	var (
		fsize   int64
		buf     = make([]byte, 32*1024)
		written int64
	)
	tmpFilePath := localPath + ".download"

	client := new(http.Client)
	client.Timeout = time.Second * 60

	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}

	fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32)
	if err != nil {
		panic(err)
	}

	if IsFileExist(localPath, fsize) {
		return err
	}

	file, err := os.Create(tmpFilePath)
	if err != nil {
		panic(err)
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic(err)
		}
	}(file)

	if resp.Body == nil {
		return errors.New("body is null")
	}
	defer resp.Body.Close()

	for {
		nr, er := resp.Body.Read(buf)
		if nr > 0 {
			nw, ew := file.Write(buf[0:nr])
			// 数据长度大于0
			if nw > 0 {
				written += int64(nw)
			}
			if ew != nil {
				err = ew
				break
			}

			if nr != nw {
				err = io.ErrShortWrite
				break
			}
		}
		if er != nil {
			if er != io.EOF {
				err = er
			}
			break
		}

		fb(fsize, written)
	}
	if err == nil {
		file.Close()
		err = os.Rename(tmpFilePath, localPath)
		fmt.Println(err)
	}

	return err
}
func createMultipartFormData(fieldName, fileName string) (bytes.Buffer, *multipart.Writer) {
	var b bytes.Buffer
	var err error
	w := multipart.NewWriter(&b)
	var fw io.Writer
	file := mustOpen(fileName)

	if fw, err = w.CreateFormFile(fieldName, file.Name()); err != nil {
		fmt.Println("Error: ", err)
	}

	if _, err = io.Copy(fw, file); err != nil {
		fmt.Println("Error: ", err)
	}

	w.Close()
	return b, w
}
func mustOpen(f string) *os.File {

	r, err := os.Open(f)

	if err != nil {

		pwd, _ := os.Getwd()

		fmt.Println("PWD: ", pwd)

		panic(err)

	}

	return r

}

func main() {
	url := "http://deepstack.local:82/v1/vision/custom/combined"
	b, w := createMultipartFormData("image", "C:\\go_sort\\temp\\person.jpg")

	req, err := http.NewRequest("POST", url, &b)

	if err != nil {
		return
	}

	req.Header.Set("Content-Type", w.FormDataContentType())
	client := &http.Client{}

	response, error := client.Do(req)

	if err != nil {
		panic(error)
	}

	defer response.Body.Close()

	fmt.Println("response Status:", response.Status)
	fmt.Println("response Headers:", response.Header)

	body, _ := ioutil.ReadAll(response.Body)
	fmt.Println("response Body:", string(body))
}

func File(r *ghttp.Request) {
	// r.Response.ServeFile("test.txt")
	r.Response.ServeFileDownload("test.txt")
}
